const { login } = require('../control/user');
const { SuccessModel, ErrorModel } = require('../model/resModel');
const crypto = require('crypto');
// 获取cookie过期时间
const getCookieExpires = () => {
    var millisecond = new Date().getTime();
    var expiresTime = new Date(millisecond + 60 * 1000 * 1);
    return expiresTime.toGMTString();
};
const handleUserRoute = (req,res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    if (method === 'GET' && path === '/api/user/login'){
        res.setHeader('Cache-Control', 'no-cache')
        const { username, password } = req.query;
        const result = login(username, password);
        return result.then(data => {
            console.log(data);

            if (data.username) {
                // 设置 session
                // res.setHeader(
                //     'Set-Cookie', `username=${data.username};path=/;httpOnly;`
                // );
                // res.setHeader('Cache-Control', 'max-age=20')

                // res.setHeader('last-modified', new Date().toUTCString())
                // if (new Date(req.headers['if-modified-since']).getTime() + 9 * 1000 > Date.now()) {
                //     console.log('协商缓存命中....')
                //     res.statusCode = 304
                //     res.end()
                //     return
                // }



                const hash = crypto.createHash('sha1').digest('hex')
                res.setHeader('Etag', hash)
                if(req.headers['if-none-match'] === hash){
                    console.log('Etag协商缓存命中.....')
                    res.statusCode = 304
                    res.end()
                    return
                }



                //req.cookie.username = data.username;
                //req.cookie.realname = data.realname;
                return new SuccessModel();
            }
            return new ErrorModel('登陆失败');
        });
    }
    // 登陆验证
    if (method === 'GET' && req.path === '/api/user/login-test') {

        res.setHeader('last-modified', new Date().toUTCString())
        if (new Date(req.headers['if-modified-since']).getTime() + 1 * 1000 > Date.now()) {
            console.log('协商缓存命中....')
            res.statusCode = 304
            res.end()
            return
        }
        // if (req.cookie.username) {
        //
        //     // res.setHeader(
        //     //     'Set-Cookie', `username=${req.cookie.username};path=/`
        //     // );
        //     return Promise.resolve(new SuccessModel({
        //         username:req.cookie.username
        //     }));
        // }
        return Promise.resolve(new ErrorModel('尚未登陆'));
    }

}
module.exports = handleUserRoute